<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="cs">
 <head>
     <meta http-equiv="content-type" content="text/html; charset=utf-8" />
     <meta http-equiv="cache-control" content="no-cache">
     <meta http-equiv="pragma" content="no-cache">
     <meta name="author" content="www.ortex.cz" />
     <title>
       NNRel by ORTEX
      </title>

     <style type="text/css" media="screen">
      body{ margin:0; pading:0; font-family: Tahoma; font-size: 11px; background-color:#f6f8fa;}
      .nowrap{padding-right: 20px; white-space: nowrap;}
     </style>

     <script type="text/javascript" src="ClientGlobalContext.js.aspx"></script>
     <script type="text/javascript" src="ort_json"></script>
     <script type="text/javascript" src="ort_jquery"></script>
     <script type="text/javascript" src="ort_XrmServiceToolkit"></script>
     
             
     <script type="text/javascript">

      var _nnrel;
      var _xrmpage;
            
      window.onload=function(){
        try{

          var rel=getDataParam('rel');
  
          if(rel===null){
            showMsg('Parameter "rel" (relationship name) not found.',true);
            return;
          }else{
            showMsg('Parameter "rel" (relationship name): '+rel);
          }
        
          _xrmpage=parent.Xrm.Page;

          if(_xrmpage.ui.getFormType()===1){
            showMsg('SAVE THE RECORD TO ENABLE THE PLUGIN.',true);
            return;
          }
          
          _nnrel=new NNRel(rel);
          
        }catch(e){
          showMsg('Code error: '+e.message,true);
        }
      };

      function showMsg(text,stop){
        document.getElementById("msgs").innerHTML+=text+"<br />";
        if(stop!==null && stop){
          document.getElementById("img").outerHTML="";
        }  
      }

      function change(which){
      
        document.getElementById("ch"+which).disabled=true;
        var res;
        
        if(document.getElementById("ch"+which).checked){
          res=XrmServiceToolkit.Soap.Associate(_nnrel._relationName, _nnrel._thisEntityName, _nnrel._thisEntityId, _nnrel._otherEntityName, [_nnrel._baseData[which]]);
        }else{
          res=XrmServiceToolkit.Soap.Disassociate(_nnrel._relationName, _nnrel._thisEntityName, _nnrel._thisEntityId, _nnrel._otherEntityName, [_nnrel._baseData[which]]);
        }

        document.getElementById("ch"+which).disabled=false;
      }      


/////get params
  function getDataParam(parname) {
     var vals = new Array();
     if (location.search !== "") {
      vals = location.search.substr(1).split("&");
      for (var i in vals) {
       vals[i] = vals[i].replace(/\+/g, " ").split("=");
      }
      //look for the parameter named 'data'
      var found = false;
      for (i in vals) {
       if (vals[i][0].toLowerCase() === "data") {
        return parseDataValue(vals[i][1],parname);
       }
      }
     }
     return null;
  }

  function parseDataValue(datavalue,parname) {
    if (datavalue !== "") {
      var vals = new Array();
      vals = decodeURIComponent(datavalue).split("&");
      for (var i in vals) {
        vals[i] = vals[i].replace(/\+/g, " ").split("=");
        if(vals[i][0]===parname){
          return vals[i][1];
        }  
      }
    }
    return null;
  }
/////


function NNRel(relationName){

  this.loadBaseData = function(){

    var fetchXml = 
      "<fetch distinct=\"false\" mapping=\"logical\" output-format=\"xml-platform\" version=\"1.0\">"+
      "  <entity name=\""+this._otherEntityName+"\">"+
      "    <attribute name=\""+this._otherEntityPrimaryField+"\" />"+
      "    <attribute name=\""+this._otherEntityName+"id\" />"+
      "    <order descending=\"false\" attribute=\""+this._otherEntityPrimaryField+"\" />"+
      "    <filter type=\"and\">"+
      "      <condition attribute=\"statecode\" value=\"0\" operator=\"eq\"/>"+
      "    </filter>"+
      "  </entity>"+
      "</fetch>";
   
    var self = this;
    XrmServiceToolkit.Soap.Fetch(fetchXml,function(r){
      self._baseData=r;
      showMsg('Base data loaded.');
      self.loadRelatedData();  
    });
    
  };

  this.loadRelatedData = function(){
    var fetchXml = 
      "<fetch mapping='logical'>" +
      "  <entity name='" + this._relationName + "'>" +
      "    <all-attributes />" +
      "    <filter>" +             
      "      <condition attribute='" + this._thisEntityName + "id' operator='eq' value ='" + this._thisEntityId + "' />" +
      "    </filter>" +
      "  </entity>" +
      "</fetch>";

    var self = this;
    XrmServiceToolkit.Soap.Fetch(fetchXml,function(r){
      self._relatedData=r;
      showMsg('Related data loaded.');
      self.drawRelations();
    });

  };
  
  //not used now
  this.refreshRelatedView = function(){
      //try for
      //related view not refreshed
      // - not loaded yet
      // - or changed of unsupported code
  
    try{
      parent.document.getElementById('area'+this._relationName+'Frame').contentWindow.document.getElementById('crmGrid_'+this._relationName).Refresh();  
    }catch(e){
      try{
        var iframe = parent.document.getElementById('area'+this._relationName+'Frame');
        iframe.src = iframe.src;    
      }catch(e){}
    }
    
  };
  
  
  // get metadata
  this.getEntityTypeCodeFromLogicalName = function(entityName) {
  
      var res =XrmServiceToolkit.Soap.RetrieveEntityMetadata(['Entity'], entityName, false);
      return res[0].PrimaryNameAttribute;
      
  };

  this.getOtherEntityName = function(relationName, secondEntity) {
      var res =XrmServiceToolkit.Soap.RetrieveEntityMetadata(['Relationships'], relationName, false);
      
      if(res[0].ManyToManyRelationships[0].Entity1LogicalName===secondEntity){
        return res[0].ManyToManyRelationships[0].Entity2LogicalName;
      }else if(res[0].ManyToManyRelationships[0].Entity2LogicalName===secondEntity){
        return res[0].ManyToManyRelationships[0].Entity1LogicalName;
      }
  };

  this.drawRelations = function(){
    document.getElementById("body").innerHTML="";
    for(var i=0;i<this._baseData.length;i++){
      var marked=false;
      for(var j=0;j<this._relatedData.length;j++){
        if(this._baseData[i].id===this._relatedData[j].attributes[this._otherEntityName+'id'].value){
          marked=true;
          break;
        }
      }
      text='<label> <span class="nowrap"><input type="checkbox" '+
            (marked?'checked="checked"':'')+
            ' id="ch'+i+'" onclick="change('+i+');" /> '+
            this._baseData[i].attributes[this._otherEntityPrimaryField].value+
            '</span> </label> ';
      document.getElementById("body").innerHTML+=text;
    }                
  };     

  this._serverUrl = _xrmpage.context.getServerUrl();

  this._thisEntityId=_xrmpage.data.entity.getId();    
  this._thisEntityName=_xrmpage.data.entity.getEntityName();    
  this._relationName=relationName;  
  
  this._otherEntityName = this.getOtherEntityName(relationName,this._thisEntityName);
  
  this._baseData=null;
  this._relatedData=null; 

  
  this._otherEntityPrimaryField=this.getEntityTypeCodeFromLogicalName(this._otherEntityName);
  if(this._otherEntityPrimaryField===null){
    showMsg('_otherEntityPrimaryField has been not loaded.',true);
  }
    
  this.loadBaseData();
  
}
//class constructor end

     </script>
 </head>
 <body>
  <div>
   <a href="#" style="float:right;" onclick="document.location=document.location; return false;"><img alt="" style="border:none;" title="reload" src="" /></a>
   <div id="body">
     <img id="img" alt="loading" title="loading please wait" src="" />
     <span id="msgs"></span> 
   </div>
  </div>
 </body>
</html>